package controllers;

import com.google.gson.JsonElement;
import play.*;
import play.modules.facebook.Facebook;
import play.mvc.*;

public class Application extends Controller {

   // port of https://github.com/facebook/php-sdk/blob/master/examples/example.php
   public static void index() {
      // Create our Application instance (replace this with your appId and secret).
      Facebook fb = new Facebook(
         "17743971608120", // your appid goes here
         "943716006e74d9b9283d4d5d8ab93204", // your app secret goes here
         true); // enable cookie support

      String uid = null;
      JsonElement me = null;

      // We may or may not have this data based on a $_GET or $_COOKIE based session.
      //
      // If we get a session here, it means we found a correctly signed session using
      // the Application Secret only Facebook and the Application know. We dont know
      // if it is still valid until we make an API call using the session. A session
      // can become invalid if it has already expired (should not be getting the
      // session back in this case) or if the user logged out of Facebook.
      if (fb.getSession() != null) {
         try {
            uid = fb.getUser();
            me = fb.api("/me");
         }
         catch (Facebook.FacebookApiException e) {
            Logger.info("session expired or user logged out: "+e.getMessage());
            // at this point fb.getSession() will return null
         }
      }

      // login or logout url will be needed depending on current user state.
      String logoutUrl = null;
      String loginUrl = null;
      if (me != null) {
         logoutUrl = fb.getLogoutUrl();
      }
      else {
         loginUrl = fb.getLoginUrl();
      }

      // This call will always work since we are fetching public data.
      JsonElement naitik = null;
      try {
         naitik = fb.api("/naitik");
      }
      catch (Facebook.FacebookApiException e) {
         Logger.error("cannot access public data: "+e.getMessage());
      }

      String appId = fb.getAppId();
      String fbSession = (fb.getSession() != null ? fb.getSession().toJson() : "{}");
      render(me, naitik, fbSession, uid, logoutUrl, loginUrl, appId);
   }
}